import toArray from './toArray';

/**
 * @name: 获取或生成dom节点
 * @param {string|Element|Element[]} selector
 * @param {Element} context
 * @return {Element[]}
 * @example getElem('div')
 */
export default function getElem(selector, context) {
  let arr = [];
  if (selector) {
    if (typeof selector === 'string') {
      selector = selector.trim();
      if (selector.indexOf('<') >= 0 && selector.indexOf('>') >= 0) {
        let tag = 'div';
        if (selector.indexOf('<li') === 0) tag = 'ul';
        if (selector.indexOf('<tr') === 0) tag = 'tbody';
        if (selector.indexOf('<td') === 0 || selector.indexOf('<th') === 0) tag = 'tr';
        if (selector.indexOf('<tbody') === 0) tag = 'table';
        if (selector.indexOf('<option') === 0) tag = 'select';
        const el = document.createElement(tag);
        el.innerHTML = selector;
        arr = toArray(el.children);
      } else {
        arr = toArray((context || document).querySelectorAll(selector));
      }
    } else if (selector.nodeType) {
      arr = [selector];
    } else {
      arr = toArray(selector).filter(el => el.nodeType);
    }
  }
  return arr;
}